﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace shuatibao.Tool
{
    public class FormToModel
    {
    }

    public static class FormToModelHelper<T> where T : new()
    {
        public static T ConvertToModel(HttpContext context)
        {
            T t = new T();
            PropertyInfo[] propertys = t.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                if (!pi.CanWrite)
                    continue;
                object value = context.Request[pi.Name];
                if (value != null && value != DBNull.Value)
                {
                    try
                    {
                        if (value.ToString() != "")
                            pi.SetValue(t, Convert.ChangeType(value, pi.PropertyType), null);//这一步很重要，用于类型转换
                        else
                            pi.SetValue(t, value, null);
                    }
                    catch
                    { }
                }
            }

            return t;
        }
    }



}